import router from './router'
import store from './store'
import NProgress from 'nprogress'
import { asyncRoutes } from './router'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })
// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  if (firstRoutePerms.includes('*')) {
    // 管理员（拷贝 - 防止重复登录同一个用户时，此变量值返回给外面后不断 push * 地址，导致左侧菜单 key 重复报错问题）
    return [...asyncRoutes]
  }
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}
// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    next()
    if (!store.getters.userInfo?.userId) {
      const permissions = await store.dispatch('user/getUserInfo')
      console.log('当前的权限数据为:', permissions)
      const firstRoutePerms = getFirstRoutePerms(permissions)
      console.log(firstRoutePerms)
      const secondRoutePerms = getSecondRoutePerms(permissions)
      console.log(secondRoutePerms)
      const perRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      console.log('最终路由表', perRoutes)
      perRoutes.push(
        // 404 地址配置为*=》匹配不存在的地址，放到过滤动态路由规则后边
        {
          path: '*',
          component: () => import('@/views/404'),
          hidden: true
        }
      )
      store.commit('user/SET_MENULIST', perRoutes)
      perRoutes.forEach(route => { router.addRoutes(route) })
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
